package com.zanclus.socialtelnet.control;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import com.zanclus.socialtelnet.entity.User;

public class TelnetSession extends Thread implements AbstractSession {
	private ArrayList<User> users = new ArrayList<User>() ;
	private Socket conn = null ;
	InputStream input = null ;
	OutputStream output = null ;

	public TelnetSession(String hostName, int port, User initial) throws Exception {
		conn = new Socket(hostName,port) ;
		input = conn.getInputStream() ;
		output = conn.getOutputStream() ;
	}

	public void subscribeUser(User joining) {
		users.add(joining) ;
	}

	public void unsubscribeUser(User leaving) throws Exception {
		users.remove(leaving) ;
		if (users.size()==0) {
			conn.close() ;
		}
	}

	public void run() {
		while (conn.isConnected()) {
			try {
				Thread.sleep(100) ;
				if (input.available()>0) {
					
				}
			} catch (Throwable t) {
				
			}
		}
	}

	@Override
	public AbstractSession init(String hostName, int portNum, User initial) {
		// TODO Auto-generated method stub
		try {
			return new TelnetSession(hostName,portNum,initial) ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null ;
		}
	}
}
